import { Card, Form, Input, Checkbox, Button, message } from "antd";
import logo from "../../assets/logo.png";
import "./index.scss";
import { useDispatch, useSelector } from "react-redux";
import { getToken } from "@/store/modules/login";
import { useNavigate } from "react-router-dom";

const Login = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const path = useSelector((state) => state.login.path);
  const onFinish = async (val) => {
    // console.log(val);
    try {
      await dispatch(getToken(val));
      message.success("登录成功", 1.5, () => {
        !!path ? navigate(path) : navigate("/my");
      });
    } catch (error) {
      message.error(error?.response?.data?.message ?? "网络繁忙，请稍后再试！");
    }
  };
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          validateTrigger={["onBlur", "onChange"]}
          onFinish={onFinish}
          initialValues={{
            mobile: "13911111111",
            code: "246810",
            remember: true,
          }}
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: "手机号为必填项！" },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: "手机号格式不正确！",
                validateTrigger: "onBlur",
              },
            ]}
          >
            <Input size="large" placeholder="请输入手机号" maxLength={11} />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: "验证码为必填项",
              },
              {
                len: 6,
                message: "验证码6个字符串",
                validateTrigger: "onBlur",
              },
            ]}
          >
            <Input size="large" placeholder="请输入验证码" maxLength={6} />
          </Form.Item>
          <Form.Item valuePropName="checked" name="remember">
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
